package cn.net.vote.data.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import cn.net.vote.data.mapper.HelloMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.net.vote.data.async.NationalData;
import cn.net.vote.data.domain.PageData;
import cn.net.vote.util.ObjectExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api("演示控制器")
@RestController
public class HomeController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RestTemplate  rest;

    @Autowired
    private HelloMapper hello;


    @Autowired
    private NationalData nationalData;

    @ApiOperation("首页")
    @GetMapping("/")
    public String index(){
        return "看见我你很幸运，表示部署成功了，开不开心？";
    }

    @ApiOperation("获取采集记录条数")
    @GetMapping("/count1")
    public int getCount1(){
        return hello.getCount();
    }


    @ApiOperation("并发多选一操作")
    @GetMapping("/any")
    public Integer getAnyByAsync() throws ExecutionException, InterruptedException {
        log.debug(String.valueOf( System.currentTimeMillis()/1000));
        CompletableFuture<Integer> i1 = nationalData.calc(8);
        CompletableFuture<Integer> i2 = nationalData.calc(4);
        CompletableFuture.anyOf(i1, i2).join();
        log.debug(String.valueOf( System.currentTimeMillis()/1000));

        log.debug(String.format("i1: %d i2: %d", i1.hashCode(), i2.hashCode()));

        if(i1.isDone()) {
            log.debug("i1");
            return i1.get();
        }
        if(i2.isDone()) {
            log.debug("i2");
            return i2.get();
        }

        return 0;
    }

    @ApiOperation("并发汇聚操作")
    @GetMapping("/all")
    public Integer getAllByAsync(){
        log.debug(String.valueOf( System.currentTimeMillis()/1000));
        CompletableFuture<Integer> i1 = nationalData.calc(6);
        CompletableFuture<Integer> i2 = nationalData.calc(3);
        CompletableFuture.allOf(i1,i2).join();
        log.debug(String.valueOf( System.currentTimeMillis()/1000));
        try {
            return i1.get() + i2.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @ApiOperation("缓存注解示例")
    @Cacheable(value = "fmcp", unless = "#result==null")
    @GetMapping("weather/{city}")
    public JSONObject getWeather(@PathVariable String city){
        log.info("http get request");
        JSONObject data = null;
        try {
            data = rest.getForObject("http://www.sojson.com/open/api/weather/json.shtml?city={city}", JSONObject.class, city);
        }catch (HttpClientErrorException e){
            log.error(e.getLocalizedMessage());
        }
        return data;
    }
    
    
    @ApiOperation("导出示例")
    @GetMapping("exportExcel/{city}")
    public ModelAndView exportExcel(@PathVariable String city){
        log.info("http get exportExcel");
        ModelAndView mv   = new ModelAndView();
        try {
        	ObjectExcelView erv = new ObjectExcelView();
        	Map<String,Object> dataMap = new HashMap<String,Object>();
        	List<String> titles = new ArrayList<String>();
			  List<PageData> varList =  null;
			  varList = new ArrayList<PageData>();
			  titles.add("测试"); 
			  PageData pd = new PageData();
			  pd.put("var", "测试");
			  varList.add(pd);
	        	dataMap.put("titles", titles);
	        	dataMap.put("varList", varList);
        	mv = new ModelAndView(erv,dataMap);
        }catch (HttpClientErrorException e){
            log.error(e.getLocalizedMessage());
        }
        return mv;
    }
}
